var express = require('express');
var router = express.Router();
const connection = require('../db/sql')
const User = require('../db/UserSql')
var QcloudSms = require("qcloudsms_js")   //短信验证码
let jwt = require('jsonwebtoken') //token
/* GET home page. */

//设置跨域访问
router.all('*', function (req, res, next) {
  //设置请求头
  //允许所有来源访问
  res.header('Access-Control-Allow-Origin', '*')
  //用于判断request来自ajax还是传统请求
  res.header("Access-Control-Allow-Headers", "Origin,token, X-Requested-With, content-Type, Accept, Authorization");
  res.header("Access-Control-Request-Headers: Origin, X-Requested-With, content-Type, Accept, Authorization");
  //允许访问的方式
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  //修改程序信息与版本
  res.header('X-Powered-By', ' 3.2.1')
  //内容类型：如果是post请求必须指定这个属性
  res.header('Content-Type', 'application/json;charset=utf-8')
  next()
})

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

//首页  --> 第一次数据
router.get('/api/index_list/0/data/1',function(req,res,next){
  res.send({
    code:1,
    data:{
      topBar:[
        {id: 0,label: '首页'},
        {id: 1,label: 'BEATS SOLO3 WIRELESS'},
        {id: 2,label: 'Beats Flex'},
        {id: 3,label: 'PowerBeats'},
        {id: 4,label: 'PowerBeats Pro'},
        {id: 5,label: 'Solo Pro'},
        {id: 6,label: 'BEATS STUDIO3 WIRELESS'},
        {id: 7,label: 'BEATS EP'},
        {id: 8,label: 'BEATS PILL+'}
      ],
      data:[
        //这是swiper的数据
        {
          id:0,
          type:'swiperList',
          data:[
            {id: 0, imgUrl: '../images/HomePage/Swiper/SwiperImg1.jpg'},
            {id: 1, imgUrl: '../images/HomePage/Swiper/SwiperImg2.jpg'},
            {id: 2, imgUrl: '../images/HomePage/Swiper/SwiperImg3.jpg'},
            {id: 3, imgUrl: '../images/HomePage/Swiper/SwiperImg4.jpg'},
            {id: 4, imgUrl: '../images/HomePage/Swiper/SwiperImg5.jpg'},
            {id: 5, imgUrl: '../images/HomePage/Swiper/SwiperImg6.jpg'},
            {id: 6, imgUrl: '../images/HomePage/Swiper/SwiperImg7.jpg'},
          ]
        },
        //icons数据
        {
          id:1,
          type:'iconsList',
          data:[
            {id: 0, imgUrl:'../images/Flex.png', title:'Beats Flex', path:'/home/BeatsFlex'},
            {id: 1, imgUrl:'../images/Solo3.png', title:'Beats Solo3', path:'/home/BeatsSolo3'},
            {id: 2, imgUrl:'../images/SoloPro.png', title:'Beats Solo Pro', path:'/home/SoloPro'},
            {id: 3, imgUrl:'../images/Studio3.png', title:'Beats Studio3', path:'/home/BeatsStudio3'},
            {id: 2, imgUrl:'../images/PowerBeats.png', title:'PowerBeats', path:'/home/PowerBeats'},
            {id: 3, imgUrl:'../images/PowerBeatsPro.png', title:'PowerBeats Pro', path:'/home/PowerBeatsPro'},
            {id: 6, imgUrl:'../images/BeatsEP.png', title:'Beats EP', path:'/home/BeatsEP'},
            {id: 7, imgUrl:'../images/BeatsPill+.png', title:'BeatsPill+', path:'/home/BeatsPill'}
          ]
        },
        //recommend数据
        {
          id:2,
          type: 'recommendList',
          data:[
            {
              id:1,
              imgUrl:'../images/HomePage/Recommend/RecommendImg2.jpg',
              name:'Beats Flex',
              content:'沉浸在自己热爱的世界中',
              price:'399.00'
            }, {
              id:2,
              imgUrl:'../images/HomePage/Recommend/RecommendImg1.jpg',
              name:'PowerBeats',
              content:'为颠覆你的运动体验而造',
              price:'1199.00'
            }, {
              id:4,
              imgUrl:'../images/HomePage/Recommend/RecommendImg3.jpg',
              name:'Studio3 Wireless ',
              content:'头戴式耳机拥有至臻音效',
              price:'2789.00'
            }, {
              id:6,
              imgUrl:'../images/HomePage/Recommend/RecommendImg4.jpg',
              name:'Powerbeats Pro',
              content:'完全无线激励你不断前行',
              price:'1888.00'
            }, {
              id:3,
              imgUrl:'../images/HomePage/Recommend/RecommendImg5.jpg',
              name:'Solo Pro',
              content:'让你尽享强劲均衡的音效',
              price:'2499.00'
            }, {
              id:5,
              imgUrl:'../images/HomePage/Recommend/RecommendImg6.jpg',
              name:'Beats EP',
              content:'享受到专业级调校的音质',
              price:'761.00'
            }
          ]
        }
      ]
    }
  })
})
//BeatsSolo3  -->第一次数据
router.get('/api/index_list/1/data/1',function (req,res,next){
  res.send({
    code:1,
    data: {
      data:[
        //swiper的数据
        {
          id:0,
          type:'swiperList',
          data:[
            {id: 0, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/solo3-wireless/pdp/202010/solo3-pdp-p03-matteblack.jpg.small.2x.jpg'},
            {id: 1, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/solo3-wireless/pdp/202010/solo3-pdp-p03-rosegold.jpg.small.1x.jpg'},
            {id: 2, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/solo3-wireless/pdp/202010/solo3-pdp-p03-citrusred.jpg.small.1x.jpg'},
          ]
        },
        //messageList
        {
          id:1,
          type:'messageList',
          data:[
            {
              id:0,
              title: 'BEATS SOLO3\n' + 'WIRELESS',
              price: '1699',
              imgUrl:'./img/ad.png'
            }
          ]
        }
      ]
    },
  })
})
//BeatsFlex  -->第一次数据
router.get('/api/index_list/2/data/1',function (req,res,next){
  res.send({
    code:1,
    data: {
      data:[
        //swiper的数据
        {
          id:0,
          type:'swiperList',
          data:[
            {id: 0, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/earphones/beats-flex/pdp/202010/beatsflex-pdp-p03-black.jpg.small.1x.jpg'},
            {id: 1, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/earphones/beats-flex/pdp/202010/beatsflex-pdp-p03-yellow.jpg.small.1x.jpg'},
            {id: 2, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/earphones/beats-flex/pdp/202010/beatsflex-pdp-p03-blue.jpg.small.1x.jpg'},
            {id: 3, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/earphones/beats-flex/pdp/202010/beatsflex-pdp-p03-gray.jpg.small.1x.jpg'},
          ]
        },
        //messageList
        {
          id:1,
          type:'messageList',
          data:[
            {
              id:0,
              title: 'BEATS SOLO3\n' + 'WIRELESS',
              price: '1699',
              imgUrl:'./img/ad.png'
            }
          ]
        }
      ]
    },
  })
})
//PowerBeats -->第一次数据
router.get('/api/index_list/3/data/1',function (req,res,next){
  res.send({
    code:1,
    data: {
      data:[
        //swiper的数据
        {
          id:0,
          type:'swiperList',
          data:[
            {id: 0, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/earphones/powerbeats/pdp/202010/powerbeats-pdp-p03-white.jpg.small.2x.jpg'},
            {id: 1, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/earphones/powerbeats/pdp/202010/powerbeats-pdp-p03-black.jpg.small.2x.jpg'},
            {id: 2, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/earphones/powerbeats/pdp/202010/powerbeats-pdp-p03-red.jpg.small.1x.jpg'},
            ]
        },
        //messageList
        {
          id:1,
          type:'messageList',
          data:[
            {
              id:0,
              title: 'BEATS SOLO3\n' + 'WIRELESS',
              price: '1699',
              imgUrl:'./img/ad.png'
            }
          ]
        }
      ]
    },
  })
})
//PowerBeatsPro -->第一次数据
router.get('/api/index_list/4/data/1',function (req,res,next){
  res.send({
    code:1,
    data: {
      data:[
        //swiper的数据
        {
          id:0,
          type:'swiperList',
          data:[
            {id: 0, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/earphones/powerbeats-pro/pdp/202010/powerbeatspro-pdp-p03-cloudpink.jpg.small.1x.jpg'},
            {id: 1, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/earphones/powerbeats-pro/pdp/202010/powerbeatspro-pdp-p03-glacierblue.jpg.small.2x.jpg'},
            {id: 2, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/earphones/powerbeats-pro/pdp/202010/powerbeatspro-pdp-p03-lavared.jpg.small.2x.jpg'},
            {id: 3, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/earphones/powerbeats-pro/pdp/202010/powerbeatspro-pdp-p03-ivory.jpg.small.2x.jpg'},
            {id: 4, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/earphones/powerbeats-pro/pdp/202010/powerbeatspro-pdp-p03-black-gray.jpg.small.2x.jpg'},
            {id: 5, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/earphones/powerbeats-pro/pdp/202010/powerbeatspro-pdp-p03-navy.jpg.small.2x.jpg'},
          ]
        },
        //messageList
        {
          id:1,
          type:'messageList',
          data:[
            {
              id:0,
              title: 'BEATS SOLO3\n' + 'WIRELESS',
              price: '1699',
              imgUrl:'./img/ad.png'
            }
          ]
        }
      ]
    },
  })
})
//Solo Pro -->第一次数据
router.get('/api/index_list/5/data/1',function (req,res,next){
  res.send({
    code:1,
    data: {
      data:[
        //swiper的数据
        {
          id:0,
          type:'swiperList',
          data:[
            {id: 0, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/solo-pro/pdp/202010/solopro-pdp-p03-ivory.jpg.small.1x.jpg'},
            {id: 1, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/solo-pro/pdp/202010/solopro-pdp-p03-black.jpg.small.1x.jpg'},
            {id: 2, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/solo-pro/pdp/202010/solopro-pdp-p03-gray.jpg.small.1x.jpg'},
          ]
        },
        //messageList
        {
          id:1,
          type:'messageList',
          data:[
            {
              id:0,
              title: 'BEATS SOLO3\n' + 'WIRELESS',
              price: '1699',
              imgUrl:'./img/ad.png'
            }
          ]
        }
      ]
    },
  })
})
//BeatsStudio3 -->第一次数据
router.get('/api/index_list/6/data/1',function (req,res,next){
  res.send({
    code:1,
    data: {
      data:[
        //swiper的数据
        {
          id:0,
          type:'swiperList',
          data:[
            {id: 0, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/studio3-wireless/pdp/202010/studio3-pdp-p03-matte_black.jpg.small.1x.jpg'},
            {id: 1, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/studio3-wireless/pdp/202010/studio3-pdp-p03-decade_blackred.jpg.small.1x.jpg'},
            {id: 2, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/studio3-wireless/pdp/202010/studio3-pdp-p03-red.jpg.small.1x.jpg'},
            {id: 3, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/studio3-wireless/pdp/202010/studio3-pdp-p03-white.jpg.small.1x.jpg'},
            {id: 4, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/studio3-wireless/pdp/202010/studio3-pdp-p03-blue.jpg.small.1x.jpg'},
            {id: 5, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/studio3-wireless/pdp/202010/studio3-pdp-p03-skyline_midnightblack.jpg.small.1x.jpg'},
            {id: 6, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/studio3-wireless/pdp/202010/studio3-pdp-p03-skyline_shadowgrey.jpg.small.1x.jpg'},
          ]
        },
        //messageList
        {
          id:1,
          type:'messageList',
          data:[
            {
              id:0,
              title: 'BEATS SOLO3\n' + 'WIRELESS',
              price: '1699',
              imgUrl:'./img/ad.png'
            }
          ]
        }
      ]
    },
  })
})
//BeatsEP -->第一次数据
router.get('/api/index_list/7/data/1',function (req,res,next){
  res.send({
    code:1,
    data: {
      data:[
        //swiper的数据
        {
          id:0,
          type:'swiperList',
          data:[
            {id: 0, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/ep/pdp/202010/beatsep-pdp-p02-blue.jpg.small.2x.jpg'},
            {id: 1, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/ep/pdp/202010/beatsep-pdp-p02-white.jpg.small.2x.jpg'},
            {id: 2, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/ep/pdp/202010/beatsep-pdp-p02-black.jpg.small.2x.jpg'},
            {id: 3, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/headphones/ep/pdp/202010/beatsep-pdp-p02-red.jpg.small.2x.jpg'},
          ]
        },
        //messageList
        {
          id:1,
          type:'messageList',
          data:[
            {
              id:0,
              title: 'BEATS SOLO3\n' + 'WIRELESS',
              price: '1699',
              imgUrl:'./img/ad.png'
            }
          ]
        }
      ]
    },
  })
})
//BeatsEP -->第一次数据
router.get('/api/index_list/8/data/1',function (req,res,next){
  res.send({
    code:1,
    data: {
      data:[
        //swiper的数据
        {
          id:0,
          type:'swiperList',
          data:[
            {id: 0, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/speakers/pill-plus/pdp/202010/pillplus-pdp-p03-white.jpg.small.1x.jpg'},
            {id: 1, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/speakers/pill-plus/pdp/202010/pillplus-pdp-p03-black.jpg.small.1x.jpg'},
            {id: 2, imgUrl: 'https://www.beatsbydre.com.cn/content/dam/beats/web/product/speakers/pill-plus/pdp/202010/pillplus-pdp-p03-red.jpg.small.1x.jpg'},
          ]
        },
        //messageList
        {
          id:1,
          type:'messageList',
          data:[
            {
              id:0,
              title: 'BEATS SOLO3\n' + 'WIRELESS',
              price: '1699',
              imgUrl:'./img/ad.png'
            }
          ]
        }
      ]
    },
  })
})


//分类数据
router.get('/api/goods/list',function (req,res,next){
  res.send({
    code:0,
    data:[//一级
      {
        id:0,
        name:'头戴式',
        data:[ //二级
          {
            id:0,
            name: '头戴式耳机',
            list:[ //三级
              {
                id: 0,
                name: 'Beasts Solo3 Wireless',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MX432?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1570119317387'
              },
              {
                id: 3,
                name: 'Beasts Solo Pro',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MRJ72?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1570059317205'
              },
              {
                id:5,
                name:'Beats EP',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/ML9D2?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1590088695000'
              },
              {
                id:4,
                name:'Beats Studio3 Wireless',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MX422?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1580420173131'
              }
            ]
          }
        ]
      },
      {
        id:1,
        name:'入耳式',
        data:[ //二级
          {
            id:1,
            name:'入耳式耳机',
            list:[  //三级
              {
                id: 1,
                name: 'Beasts Flex',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MYMC2?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1601053171000'
              },
              {
                id: 2,
                name: 'Powerbeats',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MWNX2?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1586808416047'
              },
              {
                id:6,
                name:'Powerbeats Pro',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MXY72?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1591647738000'
              }
            ]
          }
        ]
      },
      {
        id:2,
        name:'无线耳机',
        data:[ //二级
          {
            id:2,
            name: '无线耳机',
            list:[ //三级
              {
                id: 0,
                name: 'Beasts Solo3 Wireless',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MX432?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1570119317387'
              },
              {
                id: 3,
                name: 'Beasts Solo Pro',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MRJ72?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1570059317205'
              },
              {
                id:4,
                name:'Beats Studio3 Wireless',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MX422?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1580420173131'
              },
              {
                id: 1,
                name: 'Beasts Flex',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MYMC2?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1601053171000'
              },
              {
                id: 2,
                name: 'Powerbeats',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MWNX2?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1586808416047'
              },
              {
                id:6,
                name:'Powerbeats Pro',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MXY72?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1591647738000'
              }
            ]
          }

        ]
      },
      {
        id:3,
        name:'降噪耳机',
        data:[ //二级
          {
            id:3,
            name:'降噪耳机',
            list:[ //三级
              {
                id: 3,
                name: 'Beasts Solo Pro',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MRJ72?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1570059317205'
              },
              {
                id: 4,
                name:'Beats Studio3 Wireless',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MX422?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1580420173131'
              },
            ]
          }
        ]
      },
      {
        id:4,
        name:'蓝牙音箱',
        data:[ //二级
          {
            id:7,
            name:'蓝牙音响',
            list:[ //三级
              {
                id: 0,
                name: 'Beasts Pill+',
                imgUrl: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/ML4Q2_AV1?wid=572&hei=572&fmt=jpeg&qlt=95&.v=1476917090436'
              }
            ]
          }
        ]
      },
    ]
  })
})

//根据id查询对应商品
router.get('/api/goods/id',function(req,res,next){
  let id = req.query.id
  connection.query('select * from shoplist where id='+id+'',function (error,results){
    if(error) throw error
    res.send({
      code: 0,
      data: results
    })
  })
})

//商品接口
router.get('/api/goods/shopList',function (req,res,next){
  let [searchName,orderName] = Object.keys(req.query)
  let [name,order] = Object.values(req.query)
  connection.query('select * from shoplist where name like "%'+name+'%" order by '+orderName+' '+order+'',function (error,results){
    if(error) throw error;
    res.send({
      code:0,
      data:results
    })
  })
})

//登录接口
router.post('/api/login',function (req,res,next){
  //后端拿到前端传递过来的数据
  let params = {
    userName : req.body.userName,
    userPwd : req.body.userPwd
  }
  //查询用户名或者手机号是否存在
  connection.query(User.queryUserName(params),function (error,results){
    if(results.length>0){ //用户名和手机号存在
      connection.query(User.queryUserPwd(params),function (error,results){
        if(results.length>0){
          res.send({
            code:0,
            data:{
              success:true,
              msg:'登录成功',
              data:results[0]
            }
          })
        }else{ //密码不匹配
          res.send({
            code:0,
            data:{
              success:false,
              msg:'密码错误'
            }
          })
        }
      })
    }else{ //用户名和手机号不存在
      res.send({
        code:0,
        data:{
          success:false,
          msg:'不存在此用户'
        }
      })
    }
  })
})
//发送短信验证码
router.post('/api/loginCode',function (req,res,next){
  //后端拿到前端传递过来的数据
  let phone = req.body.phone

  // 短信应用 SDK AppID
  var appid = 1400187558;  // SDK AppID 以1400开头
// 短信应用 SDK AppKey
  var appkey = "dc9dc3391896235ddc2325685047edc7";
// 需要发送短信的手机号码
  var phoneNumbers = [phone];
// 短信模板 ID，需要在短信控制台中申请
  var templateId = 285590;  // NOTE: 这里的模板ID`7839`只是示例，真实的模板 ID 需要在短信控制台中申请
// 签名
  var smsSign = "三人行慕课";  // NOTE: 签名参数使用的是`签名内容`，而不是`签名ID`。这里的签名"腾讯云"只是示例，真实的签名需要在短信控制台申请
// 实例化 QcloudSms
  var qcloudsms = QcloudSms(appid, appkey);
// 设置请求回调处理, 这里只是演示，用户需要自定义相应处理回调
  function callback(err, result, resData) {
    if (err) {
      console.log("err: ", err);
    } else {
      res.send({
        code:0,
        data:{
          success:true,
          data:result.req.body.params[0]
        }
      })
    }
  }

  var ssender = qcloudsms.SmsSingleSender();
  var params = [Math.floor(Math.random()*(9999-1000))+1000];
  ssender.sendWithParam("86", phoneNumbers[0], templateId,
    params, smsSign, "", "", callback);

})
//判断是否有用户===》 没有就增加用户 总之要返回用户信息
router.post('/api/addUser',function (req,res,next){
  //后端拿到前端传递过来的数据
  let params = {
    userName:req.body.phone
  }
  //查询用户是否存在
  connection.query(User.queryUserName(params),function (error,results){
    //如果数据存在
    if(results.length>0){
      res.send({
        code: 0,
        data:{
          success: true,
          msg:'登录成功',
          data:results[0]
        }
      })
    }else {
      //如果没有，新增一条数据
      connection.query(User.insertData(params), function (err, result) {
        //查询结果给前端放回用户数据
        connection.query(User.queryUserName(params), function (e, r) {
          res.send({
            code: 0,
            data: {
              success: true,
              msg: '注册登录成功',
              data: r[0]
            }
          })
        })
      })
    }
  })
})

//增加 【购物车数据】
router.post('/api/addCart',function (req,res,next){
  let token = req.headers.token
  let phone = jwt.decode(token)
  //商品id
  var goods_id = req.body.goodsId
  //商品数量
  var goods_num = req.body.goodsNum
  //查找到当前用户
  connection.query('select * from user where phone = "'+phone.name+'"',function (error,results){
    //用户id
    let userId = results[0].id
    //查询对应的商品
    connection.query('select * from shoplist where id = "'+goods_id+'"',function (err,result){
      //商品名称
      let name = result[0].name
      //商品价格
      let price = result[0].price
      //商品图片
      let imgUrl = result[0].imgUrl

      //查找当前用户之前有没有这条数据
      connection.query('select * from goods_cart where uid = "'+userId+'" and goods_id = "'+goods_id+'"',function (er,re){
        if(re.length>0){
          //如果有就修改
          //数量叠加
          let num = goods_num+re[0].goods_num
          connection.query('update goods_cart set goods_num = "'+num+'" where uid = "'+userId+'" and goods_id = "'+goods_id+'"',function (err,result){
            res.send({
              code:0,
              data: {
                success: true,
                msg:'添加购物车成功'
              }
            })
          })
        }else{
          //如果没有就新增
          connection.query('insert into goods_cart (goods_id,goods_name,goods_num,goods_price,goods_imgUrl,uid) values ("'+goods_id+'","'+name+'","'+goods_num+'","'+price+'","'+imgUrl+'","'+userId+'")',function (e,r){
            res.send({
              code:0,
              data:{
                success:true,
                msg:'添加购物车成功'
              }
            })
          })
        }
      })
    })
  })
})
//查询 【购物车数据】
router.post('/api/selectCart',function (req,res,next){
  let token = req.headers.token
  let phone = jwt.decode(token)
  //确定哪一个用户
  connection.query('select * from user where phone = "'+phone.name+'"',function (error,results){
    let userId = results[0].id
    connection.query('select * from goods_cart where uid = "'+userId+'"',function (err,result){
      res.send({
        code:0,
        data:result
      })
    })
  })
})
//修改 【购物车数据库数据】
router.post('/api/updateNumCart',function (req,res,next){
  let token = req.headers.token
  let phone = jwt.decode(token)
  //得到前端给后端的商品id
  let goodsId = req.body.goodsId
  //得到前端给后端的修改数量
  let goodsNum = req.body.goodsNum
  //查询当前用户
  connection.query('select * from user where phone = "'+phone.name+'"',function (error,results){
    let userId = results[0].id
    //查询到商品,修改数量
    connection.query('update goods_cart set goods_num = "'+goodsNum+'" where uid = "'+userId+'" and goods_id = "'+goodsId+'"',function (err,result){
      res.send({
        code:0,
        data: {
          success: true,
          msg:'操作完成'
        }
      })
    })
  })
})
//删除 【购物车数据库数据】
router.post('/api/deleteCart',function (req,res,next){
  let id = req.body.id
  connection.query('delete from goods_cart where id = "'+id+'"',function (error,results){
    res.send({
      code:0,
      data:{
        success:true,
        msg:'删除成功'
      }
    })
  })
})

//查询【收货地址】
router.post('/api/selectAddress',function (req,res,next){
  let token = req.headers.token
  let phone = jwt.decode(token)
  //确定哪一个用户
  connection.query('select * from user where phone = "'+phone.name+'"',function (error,results){
    let userId = results[0].id
    connection.query('select * from address where uid = "'+userId+'"',function (err,result){
      res.send({
        code:0,
        data:result
      })
    })
  })
})
//删除 【收货地址】
router.post('/api/deleteAddress',function (req,res,next){
  let id = req.body.id
  connection.query('delete from address where id = "'+id+'"',function (error,results){
    res.send({
      code:0,
      data:{
        success:true,
        msg:'删除成功'
      }
    })
  })
})
//增加 【收货地址】
router.post('/api/addAddress',function(req,res,next){
  let token = req.headers.token
  let phone = jwt.decode(token)
  //收货地址id
  var id = req.body.id
  //收获地址信息
  var form = req.body.form
  var info = req.body.info

  if( id >= 0 ){  //如果是修改当前用户信息
    //查询当前用户
    connection.query('select * from user where phone = "'+phone.name+'"',function (error,results) {
      let userId = results[0].id
      //判断是否设置为默认地址
      if(form.delivery){
        //设置其他地址不为默认地址
        connection.query('update address set isDefault = 0 where uid = "'+userId+'"',function (err,result){
          //增加默认地址
          connection.query('update address set name = "'+form.name+'",tel = "'+form.tel+'",province = "'+info.province+'",city = "'+info.city+'",district = "'+info.district+'",address = "'+form.address+'",isDefault = 1 where id = "'+id+'"',function (e,r){
            res.send({
              code:0,
              data:{
                success:true,
                msg:'添加购物车成功'
              }
            })
          })
        })
      }else{
        connection.query('update address set name = "'+form.name+'",tel = "'+form.tel+'",province = "'+info.province+'",city = "'+info.city+'",district = "'+info.district+'",address = "'+form.address+'",isDefault = 0 where id = "'+id+'"',function (e,r){
          res.send({
            code:0,
            data:{
              success:true,
              msg:'添加购物车成功'
            }
          })
        })
      }
    })
  }else{  //增加新的收货地址
    //查询当前用户
    connection.query('select * from user where phone = "'+phone.name+'"',function (error,results) {
      let userId = results[0].id
      //判断是否设置为默认地址
      if(form.delivery){
        //设置其他地址不为默认地址
        connection.query('update address set isDefault = 0 where uid = "'+userId+'"',function (err,result){
          //增加默认地址
          connection.query('insert into address (name,tel,province,city,district,address,isDefault,uid) values ("'+form.name+'","'+form.tel+'","'+info.province+'","'+info.city+'","'+info.district+'","'+form.address+'",1,"'+userId+'")',function (e,r){
            res.send({
              code:0,
              data:{
                success:true,
                msg:'添加购物车成功'
              }
            })
          })
        })
      }else{
        connection.query('insert into address (name,tel,province,city,district,address,isDefault,uid) values ("'+form.name+'","'+form.tel+'","'+info.province+'","'+info.city+'","'+info.district+'","'+form.address+'",0,"'+userId+'")',function (e,r){
          res.send({
            code:0,
            data:{
              success:true,
              msg:'添加购物车成功'
            }
          })
        })
      }
    })
  }

})
//存储订单信息
router.post('/api/addorder',function (req,res,next){
  let token = req.headers.token
  let phone = jwt.decode(token)
  //商品信息
  var list = req.body.list
  /*订单
   0:支付失败
   1:未支付
   2:待支付
   3:支付成功
   */
  //商品列表
  let goodsName = []
  //订单商品总数量
  let goodsNum = 0
  //订单商品总价
  let goodsPrice = 0
  list.forEach(v => {
    if(v.checked === true){
      goodsName.push( v.goods_name )
      goodsNum += v.goods_num
      goodsPrice += v.goods_num * v.goods_price
    }
  })
  console.log(goodsName);
  //确定哪一个用户
  connection.query('select * from user where phone = "'+phone.name+'"',function (error,results){
    let userId = results[0].id

    var outTradeNo="";  //订单号
    for(var i=0;i<6;i++) //6位随机数，用以加在时间戳后面。
    {
      outTradeNo += Math.floor(Math.random()*10);
    }
    outTradeNo = new Date().getTime() + outTradeNo;  //时间戳，用来生成订单号

    console.log(outTradeNo)
    //生成订单 ===》 状态为1
    connection.query('insert into shop_orders (uid,order_id,goods_name,goods_price,goods_num,order_status) values ("'+userId+'","'+outTradeNo+'","'+goodsName+'","'+goodsPrice+'","'+goodsNum+'","1")',function (err,result){

    })
    //查询返回订单号
    connection.query('select * from shop_orders where uid = "'+userId+'" and order_status = "1" ',function (err,result){
      res.send({
        code: 0,
        data: result
      })
    })
  })
})
module.exports = router;
